/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2025. All rights reserved.
 *
 */

import process from 'process';

import { HvigorConfigReader } from '../../base/util/hvigor-config-reader.js';

/**
 * 设置daemon进程execArgv属性
 * @restartByConfigChange: 是否是hvigor-config文件触发的计算
 */

export function calcChildExecArgv(trigByConfigChange=false) {
  const childExecArgv: string[] = [...process.execArgv];

  const maxOldSpaceSize = HvigorConfigReader.getMaxOldSpaceSize(trigByConfigChange);
  const maxOldSpaceSizeArgv = `--max-old-space-size=${maxOldSpaceSize}`;
  const maxOldSpaceIndex = childExecArgv.findIndex((arg) => arg.startsWith('--max-old-space-size='));

  if (maxOldSpaceIndex === -1 || !childExecArgv[maxOldSpaceIndex]) {
    // 如果没有找到现有的 --max-old-space-size 参数，或者参数为空，则根据maxOldSpaceSize 是否有值添加参数
    childExecArgv.push(maxOldSpaceSizeArgv);
  } else {
    // 替换现有的 --max-old-space-size 参数
    childExecArgv[maxOldSpaceIndex] = maxOldSpaceSizeArgv;
  }

  const maxSemiSpaceSize = HvigorConfigReader.getMaxSemiSpaceSize(trigByConfigChange);
  const maxSemiSpaceSizeArgv = `--max-semi-space-size=${maxSemiSpaceSize}`;
  const maxSemiSpaceIndex = childExecArgv.findIndex((arg) => arg.startsWith('--max-semi-space-size='));

  if (maxSemiSpaceIndex === -1 || !childExecArgv[maxSemiSpaceIndex]) {
    // 如果没有找到现有的 --max-semi-space-size 参数，或者参数为空，maxNewSpaceSize 是否有值添加参数
    childExecArgv.push(maxSemiSpaceSizeArgv);
  } else {
    // 替换现有的 --max-semi-space-size 参数
    childExecArgv[maxSemiSpaceIndex] = maxSemiSpaceSizeArgv;
  }

  const exposeGc: boolean | undefined = HvigorConfigReader.getHvigorConfig()?.nodeOptions?.exposeGC;
  const exposeGcIndex = childExecArgv.indexOf('--expose-gc');

  if (exposeGc !== false && (exposeGcIndex === -1 || !childExecArgv[exposeGcIndex])) {
    childExecArgv.push('--expose-gc');
  } else if (exposeGc === false && (exposeGcIndex !== -1 || childExecArgv[exposeGcIndex])) {
    childExecArgv.splice(exposeGcIndex, 1);
  }
  return childExecArgv;
}
